package com.lihao.wanandroid.ui.login

import android.os.Bundle
import android.text.TextUtils
import androidx.lifecycle.Observer
import com.lihao.jetpackcore.ext.nav
import com.lihao.jetpackcore.ext.parseState
import com.lihao.jetpackcore.util.ToastUtil
import com.lihao.wanandroid.R
import com.lihao.wanandroid.app.base.BaseFragment
import com.lihao.wanandroid.app.ext.hideSoftKeyboard
import kotlinx.android.synthetic.main.fragment_register.*

/**
 * 注册界面
 */
class RegisterFragment : BaseFragment<LoginRegisterViewModel>() {

    override fun layoutId() = R.layout.fragment_register

    override fun initView(savedInstanceState: Bundle?) {
        ivClose.setOnClickListener {
            hideSoftKeyboard(activity)
            nav().navigateUp()
        }
        btnRegister.setOnClickListener {
            mViewModel.username = editUserName.text.toString()
            mViewModel.password = editPassword.text.toString()
            mViewModel.repassword = editRepassword.text.toString()
            when {
                TextUtils.isEmpty(mViewModel.username) -> {
                    ToastUtil.showShort(context, "用户名不能为空")
                }
                TextUtils.isEmpty(mViewModel.password) ||
                        TextUtils.isEmpty(mViewModel.repassword) -> {
                    ToastUtil.showShort(context, "密码不能为空")
                }
                mViewModel.password != mViewModel.repassword -> {
                    ToastUtil.showShort(context, "密码不一致，请重新输入")
                    mViewModel
                }
            }
        }
    }

    override fun lazyLoadData() {
        editUserName.setText(mViewModel.username)
    }

    override fun createObserver() {
        mViewModel.registerResult.observe(this, Observer { resultState ->
            parseState(resultState, {
                hideSoftKeyboard(activity)
                nav().navigateUp()
            }, {
                ToastUtil.showShort(context, it.message)
            })
        })
    }
}